package com.ym.b2b.ws.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.ym.b2b.buyer.dao.EmCBuyerDao;
import com.ym.b2b.buyer.sqlbean.EmCBuyer;
import com.ym.b2b.commons.conf.WebTokenUser;
import com.ym.b2b.complaint.service.EmBComplaintService;
import com.ym.b2b.complaint.sqlbean.EmBComplaint;
import com.ym.b2b.news.service.EmBNewsService;
import com.ym.b2b.news.sqlbean.EmBNews;
import com.ym.b2b.order.dao.EmShoppingCartDao;
import com.ym.b2b.order.service.EmSOrderService;
import com.ym.b2b.order.service.EmShoppingCartService;
import com.ym.b2b.order.sqlbean.EmSOrder;
import com.ym.b2b.order.sqlbean.EmSShoppingCart;
import com.ym.b2b.order.vo.OrderInfoVO;
import com.ym.b2b.product.dao.EmBProductIntroductionDAO;
import com.ym.b2b.product.service.ProductService;
import com.ym.b2b.product.sqlbean.EmBProduct;
import com.ym.b2b.product.sqlbean.EmBProductIntroduction;
import com.ym.b2b.user.service.EmCUserService;
import com.ym.b2b.user.service.UserFavoritesService;
import com.ym.b2b.user.sqlbean.EmCUser;
import com.ym.b2b.user.sqlbean.EmSUserFavorites;
import com.ym.b2b.ws.base.BaseWs;
import com.ym.b2b.ws.mobile.bean.NewsList;
import com.ym.b2b.ws.mobile.bean.ProductIntroduction;
import com.ym.b2b.ws.mobile.bean.ProductList;
import com.ym.b2b.ws.service.CustomerService;
import com.zc.commons.base.Page;
import com.zc.commons.base.Result;
import com.zc.commons.util.ZcStringUtil;

@Service
@WebService
@SOAPBinding(style = Style.RPC)
// jdk 1.6u17以上版本可不加
public class CustomerServiceImpl extends BaseWs implements CustomerService {

    private static SerializerFeature[] features = { SerializerFeature.WriteNullNumberAsZero,
            SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullBooleanAsFalse,
            SerializerFeature.DisableCircularReferenceDetect };

    @Autowired
    private EmCUserService             emCUserService;

    @Autowired
    private ProductService             productService;

    @Autowired
    private EmBNewsService             emBNewsService;

    @Autowired
    private EmSOrderService            emSOrderService;

    @Autowired
    private EmBProductIntroductionDAO  emBProductIntroductionDAO;

    @Autowired
    private EmShoppingCartService      emShoppingCartService;

    @Autowired
    private EmShoppingCartDao          emShoppingCartDao;

    @Autowired
    private UserFavoritesService       userFavoritesService;

    @Autowired
    private EmBComplaintService        emBComplaintService;

    @Autowired
    private EmCBuyerDao                emCBuyerDao;

    private WebTokenUser getToken(String buyerCode) {
        WebTokenUser webTokenUser = new WebTokenUser();
        // 查询采购商
        EmCBuyer emCBuyer = new EmCBuyer();
        emCBuyer.setBuyerCode(buyerCode);
        emCBuyer = emCBuyerDao.showEmCBuyerDetail(emCBuyer);

        webTokenUser.setPayType(emCBuyer.getPayType() == null ? -1 : emCBuyer.getPayType());
        webTokenUser.setBuyerIsValid(emCBuyer.getIsValid());
        webTokenUser.setIsBranch(emCBuyer.getIsBranch());
        webTokenUser.setBuyerCode(buyerCode);
        return webTokenUser;

    }

    /**
     * 用户登陆 @userName 登陆名 @password 密码 返回值：
     */
    @Override
    public String login(@WebParam(name = "userName")
    String userName, @WebParam(name = "password")
    String password) {
        Result ret = new Result();
        try {
            EmCUser emCuser = new EmCUser();
            emCuser.setLoginName(userName);
            emCuser.setLoginPwd(password);
            ret = emCUserService.login(emCuser);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "系统异常  请联系管理员!" + e.getMessage());
        }
        return JSON.toJSONString(ret, filter, features);
    }

    /**
     * 获取产品列表  返回List<EmBProduct> 列表
     * <p>Title: getProductListForJosn</p>
     */
    @Override
    public String getProductListForJosn(@WebParam(name = "searchWhere")
    String searchWhere, @WebParam(name = "searchType")
    String searchType, @WebParam(name = "orderBy")
    String orderBy, @WebParam(name = "typeCode")
    String typeCode, @WebParam(name = "buyerCode")
    String buyerCode, @WebParam(name = "userType")
    String userType, @WebParam(name = "childID")
    String childID, @WebParam(name = "vipFlag")
    String vipFlag, @WebParam(name = "areaCode")
    String areaCode, @WebParam(name = "page")
    String page, @WebParam(name = "pageSize")
    String pageSize) {
        Result ret = new Result();
        try {
            // check
            if (StringUtils.isBlank(pageSize)) {
                ret.setCodeResult(Result.CODE_100, "参数 pageSize分页大小 不能为空");
            }
            if (StringUtils.isBlank(page)) {
                ret.setCodeResult(Result.CODE_100, "参数 page页码 不能为空");
            }
            if (ret.getCode().equals(Result.CODE_100)) return JSON.toJSONString(ret);
            EmBProduct emBProduct = new EmBProduct();
            emBProduct.setBuyerCode(buyerCode);
            emBProduct.setSearchWhere(searchWhere);
            emBProduct.setProductTypeCode(typeCode);
            emBProduct.setApproveStatus(10);

            Page<EmBProduct> p = new Page<EmBProduct>();
            p.setPage(Integer.parseInt(page));
            p.setPageSize(Integer.parseInt(pageSize));
            p.setPageable("true");
            ret = productService.searchPageProduct(emBProduct, p);

            // 转换成 mobile实体
            List<ProductList> list = new ArrayList<ProductList>();
            for (EmBProduct l : (List<EmBProduct>) ret.getRows()) {
                ProductList vo = new ProductList();
                vo.setProductCode(l.getProductCode());
                vo.setProducingArea(l.getProducingArea());
                vo.setProductName(l.getProductName());
                vo.setStockAmount(String.valueOf(l.getStockNum()));
                vo.setPictureUrl(l.getSmallPic());
                vo.setPackingUnit(l.getPackingUnit());
                vo.setProducingName(l.getProducingName());
                vo.setRetailPrice(l.getRetailPrice());
                vo.setSalePrice(l.getSalePrice());
                list.add(vo);
            }
            ret.getRows().clear();
            ret.setRows(list);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "系统异常,请拨打客服电话!" + e.getMessage());
        }
        return JSON.toJSONString(ret, filter, features);
    }

    /**
     * 获取产品详情  productCode商品编号  获取EmBProduct intrasduction说明书 质检单quantyFile 
     * <p>Title: getProductDetailForJosn</p>
     */
    @Override
    public String getProductDetailForJosn(String productCode, String buyerCode, String userType, String areaCode) {
        Result ret = new Result();
        try {
            EmBProduct emBProduct = new EmBProduct();

            if (StringUtils.isNotBlank(buyerCode)) {
                WebTokenUser t = getToken(buyerCode);
                emBProduct.setUser(t);
            }
            emBProduct.setProductCode(productCode);
            ret = productService.showProductDetail(emBProduct);

            // 一下这段为默认EmBProductIntroduction传入手机很多值没有 一时无法搞定，故有如下零时方法
            EmBProductIntroduction emBProductIntroduction = (EmBProductIntroduction) ret.getData("emBProductIntroduction");
            ProductIntroduction p = new ProductIntroduction();
            p.setI_badness(emBProductIntroduction.getiBadness());
            p.setI_character(emBProductIntroduction.getiCharacter());
            p.setI_compose(emBProductIntroduction.getiCompose());
            p.setI_function(emBProductIntroduction.getiFunction());
            p.setI_notice(emBProductIntroduction.getiNotice());
            p.setI_packing(emBProductIntroduction.getiPacking());
            p.setI_reciprocity(emBProductIntroduction.getiReciprocity());
            p.setI_standard(emBProductIntroduction.getiStandard());
            p.setI_store(emBProductIntroduction.getiStore());
            p.setI_taboo(emBProductIntroduction.getiTaboo());
            p.setI_usage(emBProductIntroduction.getiUsage());
            p.setI_validity(emBProductIntroduction.getiValidity());

            ret.getData().remove("emBProductIntroduction");
            ret.putData("emBProductIntroduction", p);

            // ret.putData("introduction", EmBProductIntroduction);
            System.out.println("说明书：" + ret.getData("emBProductIntroduction").toString());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "服务端系统异常!" + e.getMessage());
        }
        return JSON.toJSONString(ret, filter, features);
    }

    /**
     * 获取资讯列表
     * <p>Title: getNewsListForJosn</p>
     */
    @Override
    public String getNewsListForJosn(String typeName, String searchTitle, String page, String pageSize) {

        Result ret = new Result();
        // check
        if (StringUtils.isBlank(typeName)) {
            ret.setCodeResult(Result.CODE_100, "入参：typeName 必填!");
        }
        if (StringUtils.isBlank(page)) {
            ret.setCodeResult(Result.CODE_100, "入参：page 必填!");
        }
        if (StringUtils.isBlank(pageSize)) {
            ret.setCodeResult(Result.CODE_100, "入参：pageSize 必填!");
        }
        if (ret.getCode().equals(Result.CODE_100)) return JSON.toJSONString(ret);
        try {
            EmBNews emBNews = new EmBNews();
            emBNews.setNewsTitle(searchTitle);
            emBNews.setNewsTypeName(typeName);

            Page<EmBNews> p = new Page<EmBNews>();
            p.setPageable("true");
            p.setPage(Integer.parseInt(page));
            p.setPageSize(Integer.parseInt(pageSize));

            ret = emBNewsService.searchMobilePageEmBNews(emBNews, p);

            List<NewsList> list = new ArrayList<NewsList>();
            for (EmBNews e : (List<EmBNews>) ret.getRows()) {
                NewsList vo = new NewsList();
                vo.setNewsId(e.getNewsId().toString());
                vo.setNewsTitle(e.getNewsTitle());
                vo.setCreateDate(e.getPublishDate());
                list.add(vo);
            }
            ret.setRows(list);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "服务端系统异常 联系管理员!" + e.getMessage());
        }
        return JSON.toJSONString(ret, filter, features);
    }

    @Override
    public String getNewsDetailForJosn(String newsId, String mobileType) {
        Result ret = new Result();
        // check
        if (StringUtils.isBlank(newsId)) {
            ret.setCodeResult(Result.CODE_100, "入参：newsId 必填!");
        }
        if (ret.getCode().equals(Result.CODE_100)) return JSON.toJSONString(ret);
        try {
            EmBNews emBNews = new EmBNews();
            emBNews.setNewsId(Long.parseLong(newsId));
            emBNews = emBNewsService.searchEmBNews(emBNews);
            ret.putData("emBNews", emBNews);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "服务端资讯明细接口异常!" + e.getMessage());
        }
        return JSON.toJSONString(ret, filter, features);
    }

    /**
     * 获取订单列表
     * <p>Title: getOrderListForJson</p>
     */
    @Override
    public String getOrderListForJson(String beginDate, String endDate, String buyerCode, String childID,
                                      String beginStatus, String endStatus, String page, String pageSize) {

        Result ret = new Result();
        try {
            Page<EmSOrder> p = new Page<EmSOrder>();
            p.setPageable("true");
            p.setPage(Integer.parseInt(page));
            p.setPageSize(Integer.parseInt(pageSize));

            EmSOrder emSOrder = new EmSOrder();
            emSOrder.setStartDate(beginDate);
            emSOrder.setEndDate(endDate);
            emSOrder.setBuyerCode(buyerCode);
            emSOrder.setBeginStatus(beginStatus);
            emSOrder.setEndStatus(endStatus);
            ret.setResultPage(emSOrderService.searchPageOrders(emSOrder, p));
        } catch (Exception e) {

            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "系统异常：" + e.getMessage());
        }
        return JSON.toJSONString(ret, filter, features);
    }

    /**
     * 获取订单详情
     * <p>Title: getOrderDetailForJson</p>
     */
    @Override
    public String getOrderDetailForJson(String orderCode) {
        Result ret = new Result();
        try {
            OrderInfoVO vo = new OrderInfoVO();
            vo.setOrderCode(orderCode);
            ret = emSOrderService.searchOrderDetail(vo);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "系统异常：" + e.getMessage());
        }
        return JSON.toJSONString(ret, filter, features);
    }

    /**
     * 意见反馈
     * <p>Title: addSuggestForJosn</p>
     */
    @Override
    public String addSuggestForJosn(String suggestContent, String connectPhone, String buyerCode, String type) {
        Result ret = new Result();
        if (ZcStringUtil.isBlank(suggestContent)) {
            ret.setCodeResult(Result.CODE_100, "入参 suggestContent 不能为空!");
        }
        if (ret.getCode().equals(Result.CODE_100)) return JSON.toJSONString(ret);
        try {
            EmBComplaint emBComplaint = new EmBComplaint();
            emBComplaint.setComplaintContent(suggestContent);
            emBComplaint.setConnectPhone(connectPhone);
            emBComplaint.setCreateUser(buyerCode);
            emBComplaint.setComplaintWay(type);
            // emBComplaint.setTypeId(Long.parseLong(type));
            ret = emBComplaintService.addEmBComplaint(emBComplaint);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "服务端系统异常：" + e.getMessage());
        }
        return JSON.toJSONString(ret, filter, features);
    }

    /**
     * 购物车列表
     */
    @Override
    public String getShoppingCartDetailForJosn(String buyerCode) {
        Result ret = new Result();
        if (ZcStringUtil.isBlank(buyerCode)) {
            ret.setCodeResult(Result.CODE_100, "入参 buyerCode 不能为空!");
        }
        if (ret.getCode().equals(Result.CODE_100)) return JSON.toJSONString(ret);
        try {
            EmSShoppingCart emSShoppingCart = new EmSShoppingCart();
            emSShoppingCart.setTokenUser(getToken(buyerCode));

            Page<EmSShoppingCart> page = new Page<EmSShoppingCart>();

            ret = emShoppingCartService.searchPageShoppingCart(emSShoppingCart, page);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JSON.toJSONString(ret, filter, features);
    }

    @Override
    public String getShoppingCartDetailForOrderForJosn(String isSelectAll, String shoppingCartIdStr, String mobileType,
                                                       String buyerCode, String userType, String childID,
                                                       String vipFlag, String areaCode) {
        Result ret = new Result();

        try {
            OrderInfoVO vo = new OrderInfoVO();
            WebTokenUser t = getToken(buyerCode);
            vo.setUser(t);
            vo.setBuyerCode(buyerCode);

            ret = emSOrderService.getInfoForOrder(vo);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "系统异常：" + e.getMessage());
        }
        return JSON.toJSONString(ret, filter, features);
    }

    /**
     * 加入购物车
     */
    @Override
    public String addToCatForJson(String productCode, String amount, String buyerCode) {
        Result ret = new Result();
        if (ZcStringUtil.isBlank(amount)) {
            ret.setCodeResult(Result.CODE_100, "入参 amount 不能为空!");
        }
        if (ZcStringUtil.isBlank(buyerCode)) {
            ret.setCodeResult(Result.CODE_100, "入参 buyerCode 不能为空!");
        }
        if (ZcStringUtil.isBlank(productCode)) {
            ret.setCodeResult(Result.CODE_100, "入参 productCode 不能为空!");
        }
        if (ret.getCode().equals(Result.CODE_100)) return JSON.toJSONString(ret);
        try {
            EmSShoppingCart emSShoppingCart = new EmSShoppingCart();
            if (StringUtils.isNotBlank(buyerCode)) {
                WebTokenUser t = getToken(buyerCode);
                emSShoppingCart.setTokenUser(t);
            }

            emSShoppingCart.setProductCode(productCode);
            emSShoppingCart.setAmount(Double.parseDouble(amount));
            emSShoppingCart.setBuyerCode(buyerCode);
            ret = emShoppingCartService.addShoppingCart(emSShoppingCart);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "服务端系统异常：" + e.getMessage());
        }
        return JSON.toJSONString(ret, filter, features);
    }

    @Override
    public String updateAmountToCatForJson(String shoppingCartId, String amount, String buyerCode) {
        Result ret = new Result();
        if (ZcStringUtil.isBlank(shoppingCartId)) {
            ret.setCodeResult(Result.CODE_100, "入参 shoppingCartId 不能为空!");
        }
        if (ZcStringUtil.isBlank(amount)) {
            ret.setCodeResult(Result.CODE_100, "入参 amount 不能为空!");
        }
        if (ZcStringUtil.isBlank(buyerCode)) {
            ret.setCodeResult(Result.CODE_100, "入参 buyerCode 不能为空!");
        }
        if (ret.getCode().equals(Result.CODE_100)) return JSON.toJSONString(ret);
        try {
            EmSShoppingCart emSShoppingCart = new EmSShoppingCart();
            emSShoppingCart.setShoppingCartId(Long.parseLong(shoppingCartId));
            emSShoppingCart.setAmount(Double.parseDouble(amount));
            emSShoppingCart.setBuyerCode(buyerCode);
            ret = emShoppingCartService.updateShoppingCart(emSShoppingCart);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "服务端系统异常：" + e.getMessage());
        }
        return JSON.toJSONString(ret, filter, features);
    }

    @Override
    public String deleteProductToCatForJson(String shoppingCartIdAll, String buyerCode) {
        Result ret = new Result();

        try {
            String[] cartId = shoppingCartIdAll.split(",");
            EmSShoppingCart emSShoppingCart = new EmSShoppingCart();
            emSShoppingCart.setBuyerCode(buyerCode);
            for (String c : cartId) {
                emSShoppingCart.setShoppingCartId(Long.parseLong(c));
                emShoppingCartDao.deleteShoppingCart(emSShoppingCart);
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "服务端系统异常：" + e.getMessage());
        }
        return JSON.toJSONString(ret, filter, features);
    }

    @Override
    public String addFavoriteForJosn(String productCode, String userId) {
        Result ret = new Result();
        if (ZcStringUtil.isBlank(userId)) {
            ret.setCodeResult(Result.CODE_100, "入参 userId 不能为空!");
        }
        if (ret.getCode().equals(Result.CODE_100)) return JSON.toJSONString(ret);
        try {
            EmSUserFavorites emSUserFavorites = new EmSUserFavorites();
            emSUserFavorites.setObjectId(productCode);
            emSUserFavorites.setUserId(Long.parseLong(userId));
            ret = userFavoritesService.addUserFavorites(emSUserFavorites);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "服务端系统异常：" + e.getMessage());
        }
        return JSON.toJSONString(ret, filter, features);

    }

    @Override
    public String removeFavoriteForJosn(String favoritesId) {
        Result ret = new Result();
        if (ZcStringUtil.isBlank(favoritesId)) {
            ret.setCodeResult(Result.CODE_100, "入参 favoritesId 不能为空!");
        }
        if (ret.getCode().equals(Result.CODE_100)) return JSON.toJSONString(ret);
        try {
            ret = userFavoritesService.deleteUserFavorites(Long.parseLong(favoritesId));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "服务端系统异常：" + e.getMessage());
        }
        return JSON.toJSONString(ret, filter, features);
    }

    @Override
    public String sureForOrderForJosn(String buyerAddressId, String mobileType, String buyerCode) {
        Result ret = new Result();
        if (ZcStringUtil.isBlank(buyerCode)) {
            ret.setCodeResult(Result.CODE_100, "入参 buyerCode 不能为空!");
        }
        if (ZcStringUtil.isBlank(buyerAddressId)) {
            ret.setCodeResult(Result.CODE_100, "入参 buyerAddressId 不能为空!");
        }
        if (ret.getCode().equals(Result.CODE_100)) return JSON.toJSONString(ret);
        try {
            OrderInfoVO vo = new OrderInfoVO();

            vo.setBuyerAddressId(Long.parseLong(buyerAddressId));
            vo.setUser(getToken(buyerCode));

            ret = emSOrderService.generateOrder(vo);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "服务端系统异常：" + e.getMessage());
        }
        return JSON.toJSONString(ret, filter, features);
    }

    @Override
    public String cancelOrderForJosn(String orderCode) {
        Result ret = new Result();
        if (ZcStringUtil.isBlank(orderCode)) {
            ret.setCodeResult(Result.CODE_100, "入参 orderCode 不能为空!");
        }
        if (ret.getCode().equals(Result.CODE_100)) return JSON.toJSONString(ret);
        try {
            OrderInfoVO vo = new OrderInfoVO();

            vo.setOrderCode(orderCode);
            // vo.setUser(getToken(buyerCode));
            ret = emSOrderService.cancelOrder(vo);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "服务端系统异常：" + e.getMessage());
        }
        return JSON.toJSONString(ret, filter, features);

    }

    private ValueFilter filter = new ValueFilter() {

                                   @Override
                                   public Object process(Object obj, String s, Object v) {
                                       if (v == null) return "";
                                       return v;
                                   }
                               };
}
